# -*- coding: utf-8 -*-
'''
Created on 2014/02/28

@author: deadblue
'''

from cn.twodland.togame import fanfou, model, ghost
from google.appengine.api import taskqueue
import logging
import webapp2

class FetchHandler(webapp2.RequestHandler):
    '''
    定时从饭否抓取提醒和私信，存入数据库并创建处理队列
    '''
    def get(self):
        # 读取最后处理的问题
        pc = model.ProblemConfig.get_by_key_name('status_problem')
        last_status_id = pc.last_id if pc is not None else None
        # 读取提醒
        client = fanfou.APIClient()
        statuses = client.status_mentions(last_status_id)
        for status in reversed(statuses):
            # 存入数据库
            last_status_id = status['id']
            sp = model.StatusProblem(key_name=status['id'])
            sp.status_id = status['id']
            sp.text = status['text']
            sp.user_id = status['user']['id']
            sp.user_name = status['user']['name']
            sp.state = 0
            sp.save()
            logging.info('save status: %s' % status['id'])
            # 创建处理任务
            taskqueue.add(queue_name='togame', url='/deal_status', 
                          params={'problem_id' : status['id']})
        # 创建或更新ProblemConfig
        if pc is None:
            pc = model.ProblemConfig(key_name='status_problem')
        pc.last_id = last_status_id
        pc.save()
        # 读取私信
        # 似乎需要权限，暂不实现
#         messages = client.message_inbox()
#         for message in reversed(messages):
#             # 存入数据库
#             mp = db.MessageProblem(key_name=message['id'])
#             mp.message_id = message['id']
#             mp.text = message['text']
#             mp.user_id = message['sender']['id']
#             mp.user_name = message['sender']['name']
#             mp.state = 0
#             mp.save()
#             logging.info('save message: %s' % message['id'])
#             # 创建处理任务
#             taskqueue.add(queue_name='togame', url='/deal_message', 
#                           params={'problem_id' : status['id']})
        logging.debug('fetch done!')

class DealStatusHandler(webapp2.RequestHandler):
    '''
    处理一个公开请求
    '''
    def post(self):
        status_id = self.request.get('problem_id')
        if status_id is not None:
            # 读取问题信息
            sp = model.StatusProblem.get_by_key_name(status_id)
            # 处理问题
            answer = ''
            try:
                answer = '@%s 结果发表o(*≧▽≦)ツ：' % sp.user_name
                result = ghost.deal(sp.user_name, sp.text)
                for option in result['options']:
                    percent = str(option['score'])
                    percent = '%s.%s%%' % (percent[:-2], percent[-2:])
                    answer += '%s（%s）；' % (option['option'], percent)
                client = fanfou.APIClient()
                client.status_update(answer, status_id)
                sp.state = 1
            except:
                sp.state = 2
            # 更新问题状态
            sp.save()

# 私信处理需要API权限，暂不实现
class DealMessageHandler(webapp2.RequestHandler):
    '''
    处理一个私信请求
    '''
    def post(self):
        logging.info('hello, world!!')
